package com.yxkj.syh.app.huarong.activities.home;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.FrameLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.syh.app.basic.base.BaseFragment;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.adps.ReturnCarListAdp;
import com.yxkj.syh.app.huarong.bean.PagesRequest;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.FragmentHomeBinding;
import com.yxkj.syh.app.huarong.views.AddressDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomeVM> {

    private PagesRequest pagesRequest;
    private ReturnCarListAdp mReturnCarListAdp;
    private AddressDialog addressDialog;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getViewModelId() {
        return BR.homeVM;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        mReturnCarListAdp = new ReturnCarListAdp();
        mVDBinding.rvReturnCars.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        mReturnCarListAdp.bindToRecycleView(mVDBinding.rvReturnCars);
        mReturnCarListAdp.setOnViewClick(car -> {
            ARouter.getInstance().build(ArouterPath.RETURN_CAR_ACTIVITY).withLong("id", car.getId()).navigation();
        });

        mVDBinding.srlReturnCars.setOnLoadMoreListener(refreshLayout -> {
            pagesRequest.setPageIndex(pagesRequest.getPageIndex().intValue() + 1);
            mViewModel.getReturnCars(pagesRequest);
        });
        mVDBinding.srlReturnCars.setOnRefreshListener(refreshLayout -> {
            pagesRequest.setPageIndex(1);
            pagesRequest.getQueryList().clear();
            mReturnCarListAdp.clear();
            mViewModel.getReturnCars(pagesRequest);
        });
        mVDBinding.srlReturnCars.setEnableLoadMore(false);


        mVDBinding.llArea.setOnClickListener(v -> {
            if (addressDialog == null) {
                addressDialog = new AddressDialog(getActivity());
                addressDialog.setOnAddressSelectedListener((province, city, county, street) -> {
                    addressDialog.cancel();
                    StringBuffer bufferName = new StringBuffer();
                    StringBuffer bufferCode = new StringBuffer();
                    if (province.id > 1) {
                        bufferName.append(province.name);
                        bufferCode.append(mViewModel.getAreaPlusId(1, province.id));
                    }else {
                        bufferName.append("全国");
                    }
                    if (city != null) {
                        if (city.id > 1) {
                            bufferCode.append(",").append(mViewModel.getAreaPlusId(2, city.id));
                            bufferName.append(city.name);
                        }
                        if (county != null) {
                            if (county.id > 1) {
                                bufferCode.append(",").append(mViewModel.getAreaPlusId(3, county.id));
                                bufferName.append(county.name);
                            }
                        }
                    }
                    mViewModel.ofArea.set(bufferName.toString());
                    pagesRequest.getQueryList().clear();
                    if (!TextUtils.isEmpty(bufferCode.toString())) {
                        PagesRequest.SqlParam sqlParam = new PagesRequest.SqlParam();
                        sqlParam.setKey("o.endAreaIds");
                        sqlParam.setOper(":");
                        sqlParam.setValue(bufferCode.toString());
                        pagesRequest.getQueryList().add(sqlParam);
                    }
                    pagesRequest.setPageIndex(1);
                    mReturnCarListAdp.clear();
                    mViewModel.getReturnCars(pagesRequest);
                });
                addressDialog.getSelector().setAddressProvider(mViewModel.addressProvider);
            }
            addressDialog.show();
        });

        //消息 下移状态栏的高度
        FrameLayout.LayoutParams flMsgParams = (FrameLayout.LayoutParams) mVDBinding.flMsg.getLayoutParams();
        flMsgParams.topMargin = ImmersionBar.getStatusBarHeight(this);
        mVDBinding.flMsg.requestLayout();
    }

    @Override
    protected void initData() {
        pagesRequest = new PagesRequest();
        pagesRequest.setPageIndex(1);
        pagesRequest.setPageSize(10);
        pagesRequest.setSortFields("o.createTime_d");

        List<PagesRequest.SqlParam> sqlParams = new ArrayList<>();
        pagesRequest.setQueryList(sqlParams);

        mViewModel.getReturnCars(pagesRequest);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldReturnCarsResponse.observe(this, carResponse -> {
            if (mVDBinding.srlReturnCars.isRefreshing()) {
                mVDBinding.srlReturnCars.finishRefresh();
            } else if (mVDBinding.srlReturnCars.isLoading()) {
                mVDBinding.srlReturnCars.finishLoadMore();
            }
            if (carResponse != null) {
                if (pagesRequest.getPageIndex() == 1) {
                    mReturnCarListAdp.setNewData(carResponse.getData().getRecords());
                } else {
                    mReturnCarListAdp.addAll(carResponse.getData().getRecords());
                }
                if (pagesRequest.getPageIndex() < carResponse.getData().getPages()) {
                    mVDBinding.srlReturnCars.setEnableLoadMore(true);
                } else {
                    mVDBinding.srlReturnCars.setEnableLoadMore(false);
                }
            } else {
                mReturnCarListAdp.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void visibleAgain() {
        pagesRequest.setPageIndex(1);
        pagesRequest.getQueryList().clear();
        mReturnCarListAdp.clear();
        mViewModel.getReturnCars(pagesRequest);
    }
}
